package fr.louloutes.lolshooter.engine.sprites;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;

/**
 * Class LolSprite: sprite handling
 * 
 * 
 * @author Louloute
 * 
 */
public class LolSprite
{

	public Rect rect;
	public Rect collisionRect;
	Bitmap b;
	boolean isDestroyed = false;

	/**
	 * Constructor with initializations
	 * 
	 * @param res
	 * @param resId
	 */
	public LolSprite( Resources res, int resId )
	{
		b = BitmapFactory.decodeResource( res, resId );
		rect = new Rect( 0, 0, b.getWidth(), b.getHeight() );
		collisionRect = rect;
	}

	/**
	 * Empty constructor
	 */
	protected LolSprite()
	{

	}

	/**
	 * Set center coordinates
	 * 
	 * @param x
	 * @param y
	 */
	public void setCenter( int x, int y )
	{
		int width = ( int ) ( rect.right - rect.left );
		int height = ( int ) ( rect.bottom - rect.top );
		assignBounds( x, y, width, height );
	}

	/**
	 * Assign boundaries to sprite
	 * 
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 */
	private void assignBounds( int x, int y, int width, int height )
	{
		rect.left = x - width / 2;
		rect.top = y - height / 2;
		rect.right = x + ( width + 1 ) / 2;
		rect.bottom = y + ( height + 1 ) / 2;
	}

	/**
	 * Draw sprite on canvas
	 * 
	 * @param c
	 */
	public void paint( Canvas c )
	{
		if ( !isDestroyed )
		{
			// Paint paint = new Paint();
			b.getPixel( 0, 0 );
			c.drawBitmap( b, rect.left, rect.top, null );
		}
	}

	/**
	 * Collision detection with another sprite
	 * 
	 * @param sprite
	 * @return
	 */
	public boolean collide( LolSprite sprite )
	{
		return collisionRect.intersect( sprite.collisionRect );
	}

	public void rotate( int degree )
	{
		Matrix mtx = new Matrix();
		mtx.postRotate( degree );
		Bitmap rotatedBMP = Bitmap.createBitmap( b, 0, 0, b.getWidth(),
				b.getHeight(), mtx, true );
		b = rotatedBMP;
	}

}
